<?php

namespace app\api\controller\product;

use think\Controller;
use think\Request;

class Buy extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->AddressModel = model('User.Address');
        $this->OrderModel = model('Order.Order');
        $this->OrderProductModel = model('Order.OrderProduct');
        $this->CartModel = model('Product.Cart');
        $this->UserModel = model('User.User');
        $this->RecordModel = model('User.Record');
        $this->ProductModel = model('Product.Product');
    }

    public function index()
    {
        $userid = $this->request->param('userid');
        $addr = $this->AddressModel->where(['userid' => $userid, 'status' => 1])->find();
        if (!$addr) {
            $this->error('暂无收货地址');
        }
        $this->success('查询成功', null, $addr);
    }

    public function ProList()
    {
        $ids = $this->request->param('id');
        // halt($list);
        $data = model('Product.Cart')->with('product')->whereIn('cart.id', $ids)->select();
        if (!$data) {
            $this->error('暂无数据');
        }
        $this->success('查询成功', null, $data);
        // halt($data);
    }

    // 购买
    /**
     *  1、删除购物车对应商品列表
     *  2、订单表新增数据
     *  3、订单商品表添加数据
     *  4、更新用户积分
     *  5、新增消费记录
     */
    public function confirm()
    {
        $userid = $this->request->param('userid');
        $ids = $this->request->param('ids');
        $addrid = $this->request->param('addrid');
        $content = $this->request->param('content');

        $CartList = model('Product.Cart')->with('product')->whereIn('cart.id', $ids)
            ->where(['userid' => $userid])->select();
        $address = model('User.Address')->find($addrid);
        $user = model('User.User')->find($userid);

        if (!$CartList) {
            $this->error('订单结算失败');
        }

        if (!$user) {
            $this->error('请先登录');
        }

        $total = 0;

        foreach ($CartList as $key => $item) {
            // 购买商品数量是否小于商品库存
            if ($item['nums'] > $item['product']['stock']) {
                $this->error($item['product']['name'] . '商品库存不足，请重试');
            }
            // 用户积分是否足够下单
            $point = bcsub($user['point'], $item['total']);
            // halt($point);
            if ($point < 0) {
                // halt("积分不足");
                $this->error('您的积分不足，请及时充值');
            }

            if (!$address) {
                $this->error('收货地址不存在，请重试');
            }
            // 计算订单总价
            $total += $item['total'];
        }
        // 开启事务
        $this->OrderModel->startTrans();
        $this->OrderProductModel->startTrans();
        $this->CartModel->startTrans();
        $this->UserModel->startTrans();
        $this->RecordModel->startTrans();
        $this->ProductModel->startTrans();

        // 订单数据
        $OrderData = [
            'userid' => $userid,
            'addrid' => $addrid,
            'content' => $content,
            'status' => 1,
            'total' => $total,
            'code' =>  build_code('ASK'),
        ];

        $OrderStatus = $this->OrderModel->validate('common/Order/Order')->save($OrderData);
        if ($OrderStatus == false) {
            $this->error($this->OrderModel->getError());
        }

        // 订单商品数据
        $OrderProductData = [];
        foreach ($CartList as $item) {
            $OrderProductData[] = [
                'userid' => $userid,
                'orderid' => $this->OrderModel->id,
                'proid' => $item['product']['id'],
                'nums' => $item['nums'],
                'price' => $item['price'],
                'total' => $item['total'],
            ];
        }
        $OrderProductStatus = $this->OrderProductModel->validate('common/Order/OrderProduct')
            ->saveAll($OrderProductData);
        if ($OrderProductStatus == false) {
            $this->OrderModel->rollback();
            $this->error($this->OrderProductModel->getError());
        }

        // 删除购物车数据
        $CartStatus = $this->CartModel->whereIn('id', $ids)->delete();
        if ($CartStatus == false) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->error($this->CartModel->getError());
        }

        // 更新用户积分
        $pointData = [
            'id' => $user['id'],
            'point' => bcsub($user['point'], $total)
        ];
        $UserStatus = $this->UserModel->isUpdate(true)->save($pointData);
        if ($UserStatus == false) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->error($this->UserModel->getError());
        }

        $proname = '';
        // 新增消费记录
        foreach ($CartList as $item) {
            $proname .= '【' . $item['product']['name'] . '】';
        }
        $time = date('Y-m-d H:m', time());
        // halt($time);
        $RecordData = [
            'userid' => $user['id'],
            'point' => $total,
            'content' => '您在【'. $time .'】购买了' . $proname . '共消费了【' . $total . '】积分',
            'state' => 5
        ];
        // halt($RecordData);
        $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
        if ($RecordStatus == false) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->error($this->RecordModel->getError());
        }

        // 更新商品库存
        $ProductData = [];
        foreach ($CartList as $item) {
            $ProductData[] = [
                'id' => $item['product']['id'],
                'stock' => bcsub($item['product']['stock'], $item['nums'])
            ];
        }
        $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

        if ($ProductStatus == false) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $this->error($this->ProductModel->getError());
        }

        if ($OrderStatus === FALSE || $OrderProductStatus === FALSE || $CartStatus === FALSE || $UserStatus === FALSE || $RecordStatus === FALSE || $ProductStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $this->ProductModel->rollback();
            $this->error('下单失败');
        } 
        else {
            $this->OrderModel->commit();
            $this->OrderProductModel->commit();
            $this->CartModel->commit();
            $this->UserModel->commit();
            $this->RecordModel->commit();
            $this->ProductModel->commit();
            $this->success('下单成功', '/order/info', ['orderid' => $this->OrderModel->id]);
        }
    }

    //  删除 购物车 商品
    public function del () {
        $id = $this->request->param('id');
        $cart = $this->CartModel->where('id', $id)->delete();
        if ($cart == false) {
            $this->error('未知错误');
        }
        $this->success('删除成功', null, $id);
    }
}
